package com.ys.service.purchase.impl;

import com.alibaba.fastjson.JSON;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.business.TpProductActive;
import com.ys.entity.purchase.*;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.purchase.TcgPurchaseByOrderEnum;
import com.ys.enume.purchase.TcgPurchasePlanGoodsEnum;
import com.ys.mapper.product.ProductMapper;
import com.ys.mapper.purchase.*;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.purchase.Api1688Service;
import com.ys.service.purchase.TcgPurchaseByOrderService;
import com.ys.service.purchase.TcgPurchaseByPlanService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.util.ToolUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 采购订单
 */
@Service("tcgPurchaseOrderService")
public class TcgPurchaseByOrderServiceImpl implements TcgPurchaseByOrderService {
	private static final Logger logger = LoggerFactory.getLogger(TcgPurchaseByOrderServiceImpl.class);

	@Autowired
	private TcgPurchaseByOrderMapper tcgPurchaseByOrderMapper;

	@Autowired
	private TcgPurchaseByOrderSonMapper tcgPurchaseByOrderSonMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

	@Autowired
	private TcgPurchaseByPlanService tcgPurchasePlanService;

	@Autowired
	private CommonApiService<TcgPurchaseByOrder> commonApiService;

	@Autowired
	private Api1688Service api1688Service;

	@Autowired
	private TcgPurchasePlanGoodsMapper tcgPurchasePlanGoodsMapper;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private TcgPurchaseOrderPayMapper tcgPurchaseOrderPayMapper;

	@Autowired
	private TcgPurchaseByOrderNpMapper tcgPurchaseByOrderNpMapper;


	private final ReentrantLock lock = new ReentrantLock();//同步锁


	//拼接api发送的地址信息
	public String getApiAddr(TcgPurchaseAddress tcgPurchaseAddress,TcgPurchaseByOrder entity)throws Exception{
		StringBuilder apiAddrSend = new StringBuilder();

		//获取子列表信息
		List<TcgPurchaseByOrderSon> sonList = new TcgPurchaseByOrderSon().setPid(entity.getId()).queryList();
		//拼接子件信息
		int row = 0;
		StringBuilder sonInfo = new StringBuilder();
		for(TcgPurchaseByOrderSon sonItem:sonList){
			if(row==0){
				sonInfo.append(sonItem.getSubCode());
			}else {
				String[] codeArr = sonItem.getSubCode().split("-");
				if(codeArr!=null && codeArr.length>1){
					sonInfo.append(codeArr[1]);
				}
			}
			row++;
		}

		apiAddrSend.append(tcgPurchaseAddress.getVGjH())
				.append(',')
				.append(tcgPurchaseAddress.getVSfH())
				.append(',')
				.append(tcgPurchaseAddress.getVDsH())
				.append(',')
				.append(tcgPurchaseAddress.getVCqH())
				.append(',')
				.append(tcgPurchaseAddress.getVDzH())
				.append('(')
				.append(entity.getBid())
				.append(',')
				.append(sonInfo)
				.append(')');

		return apiAddrSend.toString();
	}


	/**
	 * 由计划单新增采购订单
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public synchronized R addByPlan(Long goodsId,String planBid) throws Exception{
		logger.info("新增传参:"+goodsId+"，用户："+ShiroUtils.getUserId());

		int isAdd = new TcgPurchaseByOrder().setPurchasePlanGoodsId(goodsId).count();
		if(isAdd>0){
			logger.info(goodsId+"已生成过采购订单");
			return R.error("已生成过采购订单");
		}
		List<Map<String,Object>> planSonList = tcgPurchasePlanService.getItemListToOrder(goodsId,planBid);
		logger.info("新增传参planSonList:"+planSonList);
		//获取计划单母件表信息
		TcgPurchasePlanGoods tcgPurchasePlanGoods = new TcgPurchasePlanGoods().setId(goodsId).queryFirst();
		if(planSonList!=null && planSonList.size()>0 && tcgPurchasePlanGoods!=null && tcgPurchasePlanGoods.getPbid()!=null){

		    //获取采购计划单信息
            TcgPurchaseByPlan tcgPurchasePlan = new TcgPurchaseByPlan().setBid(tcgPurchasePlanGoods.getPbid()).queryFirst();
            if(tcgPurchasePlan==null || tcgPurchasePlan.getId()==null){
                return R.error();
            }
			//获取采购地址表信息
			TcgPurchaseAddress tcgPurchaseAddress = new TcgPurchaseAddress().setId(tcgPurchasePlan.getPurchaseAddressId()).queryFirst();
            /*
			//获取单号
			String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseByOrder);

			//保存主表信息
			TcgPurchaseByOrder entity = new TcgPurchaseByOrder();
			entity.setBid(bid);
			entity.setPlanBid(tcgPurchasePlanGoods.getPbid());//采购计划单号
			entity.setPurchasePlanGoodsId(goodsId);//采购计划母件表id
			entity.setVgsbm(tcgPurchasePlan.getVgsbm());//运营公司编码
			entity.setPurchaseAddressId(tcgPurchasePlan.getPurchaseAddressId());//采购公司地址表Id
			entity.setSpBm(tcgPurchasePlanGoods.getSpBm());//商品编码
			entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.ORDER_PRODUCE.value);//订单状态
			entity.setAliAccount(api1688Service.get1688ResourceOwner());//1688账号
			entity.setIsPay(0);//付款状态(0未付款、1已付款)
			//entity.setSupplierId(supplierId);//供应商id
			entity.setStatus(1);//状态

			BigDecimal orderAmountExpect = BigDecimal.ZERO;//预计采购订单金额（采购计划对应子件子件预估总价和）
			for(Map<String,Object> item:planSonList){
				orderAmountExpect = orderAmountExpect.add(new BigDecimal(item.get("subTotalPrice").toString()));
			}
			entity.setOrderAmountExpect(orderAmountExpect);
			tcgPurchaseByOrderMapper.insert(entity);

			//保存子表信息
			for(Map<String,Object> item:planSonList){
				TcgPurchaseByOrderSon sonInfo = new TcgPurchaseByOrderSon();
				sonInfo.setStatus(1);
				sonInfo.setPid(entity.getId());//母表id（TCG_PurchaseByOrder）
				if(checkUtil.isNotNullByObject(item.get("purchasePlanSonId"))) sonInfo.setPurchasePlanSonId(Long.parseLong(item.get("purchasePlanSonId").toString()));//采购计划子件表id（TCG_PurchaseByPlanSon）
				if(checkUtil.isNotNullByObject(item.get("subCode"))) sonInfo.setSubCode(item.get("subCode").toString());//子件商品编码
				if(checkUtil.isNotNullByObject(item.get("goodsId"))) sonInfo.setGoodsId(item.get("goodsId").toString());//1688铺货商品ID
				if(checkUtil.isNotNullByObject(item.get("skupRoperty"))) sonInfo.setSku(item.get("skupRoperty").toString());//SKU属性
				if(checkUtil.isNotNullByObject(item.get("skuId"))) sonInfo.setSkuId(item.get("skuId").toString());//skuId
				if(checkUtil.isNotNullByObject(item.get("specId"))) sonInfo.setSpecId(item.get("specId").toString());//specId
				if(checkUtil.isNotNullByObject(item.get("tradeName"))) sonInfo.setTradeName(item.get("tradeName").toString());//商品标题
				if(checkUtil.isNotNullByObject(item.get("skuCode"))) sonInfo.setSkuCode(item.get("skuCode").toString());//sku编码
				if(checkUtil.isNotNullByObject(item.get("supplierId"))) sonInfo.setSupplierId(item.get("supplierId").toString());//供应商id
				tcgPurchaseByOrderSonMapper.insert(sonInfo);

			}

             */

            //根据子件编码去重
			List<Map<String,Object>> planSonListGroupBySubCode = ToolUtil.groupsByList(planSonList,e->e.get("subCode").toString());
			logger.info("根据子件编码去重planSonListGroupBySubCode:"+planSonListGroupBySubCode);

			//根据供应商id进行拆分
			Map<String, List<Map<String, Object>>> groupsByCode = planSonListGroupBySubCode
					.stream()
					.collect(Collectors.groupingBy(e->e.get("supplierId").toString()));
			List<String> supplierIdList = new ArrayList<>();
			//遍历，填入去重的供应商id
			groupsByCode.forEach((k, v) -> supplierIdList.add(v.get(0).get("supplierId").toString()));


			String createMonth = DateUtil.getYYYYMM(new Date());//创建时的月份信息
			int planToOrderNum = supplierIdList.size();//计划单拆分订单数量

			int monthNo = productMapper.getPurchaseByOrderMonthNoByMonth(createMonth);//当月订单序号
			monthNo++;
			int planToOrderNo = 0;//计划单拆分订单序号
			//遍历供应商id，新增订单信息
			for(String supplierId:supplierIdList){
				planToOrderNo++;

				List<Map<String,Object>> planSonListBySupplierId = planSonListGroupBySubCode.stream()
						.filter(item->item.get("supplierId")!=null && item.get("supplierId").toString().equals(supplierId))
						.collect(Collectors.toList());

				BigDecimal negotiatedPrice = BigDecimal.ZERO;
				TcgPurchaseByOrderNp  tcgPurchaseByOrderNp = new TcgPurchaseByOrderNp().setSpBm(tcgPurchasePlanGoods.getSpBm()).queryFirst();
				if (tcgPurchaseByOrderNp != null){
					negotiatedPrice = tcgPurchaseByOrderNp.getNegotiatedPrice();
				}
				//获取单号
				String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseByOrder);

				//保存主表信息
				TcgPurchaseByOrder entity = new TcgPurchaseByOrder();
				entity.setBid(bid);
				entity.setPlanBid(tcgPurchasePlanGoods.getPbid());//采购计划单号
				entity.setPurchasePlanGoodsId(goodsId);//采购计划母件表id
				entity.setVgsbm(tcgPurchasePlan.getVgsbm());//运营公司编码
				entity.setPurchaseAddressId(tcgPurchasePlan.getPurchaseAddressId());//采购公司地址表Id
				entity.setSpBm(tcgPurchasePlanGoods.getSpBm());//商品编码
				entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.ORDER_PRODUCE.value);//订单状态
				entity.setAliAccount(api1688Service.get1688ResourceOwner());//1688账号
				entity.setIsPay(0);//付款状态(0未付款、1已付款)
				//entity.setSupplierId(supplierId);//供应商id
				entity.setStatus(1);//状态
				entity.setNegotiatedPrice(negotiatedPrice);//协议价
				entity.setOperateStatus(TcgPurchaseByOrderEnum.OperateStatus.NORMAL.value);

				BigDecimal orderAmountExpect = BigDecimal.ZERO;//预计采购订单金额（采购计划对应子件子件预估总价和）
				for(Map<String,Object> item:planSonListBySupplierId){
					orderAmountExpect = orderAmountExpect.add(new BigDecimal(item.get("subTotalPrice").toString()));
				}
				entity.setOrderAmountExpect(orderAmountExpect);

				entity.setPlanToOrderNo(planToOrderNo);//计划单拆分订单序号
				entity.setPlanToOrderNum(planToOrderNum);//计划单拆分订单数量
				entity.setCreateMonth(createMonth);//创建时的月份信息
				entity.setMonthNo(monthNo);//当月订单序号
				tcgPurchaseByOrderMapper.insert(entity);
				int row = 0;
				String firstSubCode = "";
				//保存子表信息
				for(Map<String,Object> item:planSonListBySupplierId){
					TcgPurchaseByOrderSon sonInfo = new TcgPurchaseByOrderSon();
					sonInfo.setStatus(1);
					sonInfo.setPid(entity.getId());//母表id（TCG_PurchaseByOrder）
					if(checkUtil.isNotNullByObject(item.get("purchasePlanSonId"))) sonInfo.setPurchasePlanSonId(Long.parseLong(item.get("purchasePlanSonId").toString()));//采购计划子件表id（TCG_PurchaseByPlanSon）
					if(checkUtil.isNotNullByObject(item.get("subCode"))) sonInfo.setSubCode(item.get("subCode").toString());//子件商品编码
					if(checkUtil.isNotNullByObject(item.get("goodsId"))) sonInfo.setGoodsId(item.get("goodsId").toString());//1688铺货商品ID
					if(checkUtil.isNotNullByObject(item.get("skupRoperty"))) sonInfo.setSku(item.get("skupRoperty").toString());//SKU属性
					if(checkUtil.isNotNullByObject(item.get("skuId"))) sonInfo.setSkuId(item.get("skuId").toString());//skuId
					if(checkUtil.isNotNullByObject(item.get("specId"))) sonInfo.setSpecId(item.get("specId").toString());//specId
					if(checkUtil.isNotNullByObject(item.get("tradeName"))) sonInfo.setTradeName(item.get("tradeName").toString());//商品标题
					if(checkUtil.isNotNullByObject(item.get("skuCode"))) sonInfo.setSkuCode(item.get("skuCode").toString());//sku编码
					if(checkUtil.isNotNullByObject(item.get("supplierId"))) sonInfo.setSupplierId(item.get("supplierId").toString());//供应商id
					if(row==0){
						firstSubCode = sonInfo.getSubCode();
					}
					tcgPurchaseByOrderSonMapper.insert(sonInfo);
					row++;
				}


				//拼接api采购地址
				entity.setApiAddrSend(getApiAddr(tcgPurchaseAddress,entity));

				if(tcgPurchasePlan.getRemark()!=null){
					entity.setRemark(tcgPurchasePlan.getRemark());
				}

				tcgPurchaseByOrderMapper.update(entity);

			}
			//修改计划单状态
			TcgPurchasePlanGoods entity = new TcgPurchasePlanGoods().setId(goodsId);
			entity.setOrderStatus(TcgPurchasePlanGoodsEnum.OrderStatus.ORDER_YES.value);
			tcgPurchasePlanGoodsMapper.update(entity);
		}

		return R.ok();
	}


	/*
	//审核
	@Override
	public R examine(Long goodsId,String planBid,int operateStatus) throws Exception{
		//获取可审核的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getExamineStatus();

		List<Map<String,Object>> sonList = new TcgPurchaseByOrder()
				.addLeftJoin("TCG_PurchaseByOrderSon B ON B.Pid = A.Id")
				.addField("B.Sku sku")
				.addField("B.SkuCode skuCode")
				.addField("B.RealitySku realitySku")
				.setPurchasePlanGoodsId(goodsId)
				.setPlanBid(planBid)
				.setOperateStatus(operateStatus)
				.where("A.OrderStatus IN ("+TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList)+")")
				//.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688.value)
				.setStatus(1)
				.queryMap();

		//验证子列表 SKU属性与实际SKU属性是否一致
		//List<TcgPurchaseByOrderSon> sonList = new TcgPurchaseByOrderSon().setPid(id).queryList();
		if(sonList ==null || sonList.size()<=0){
			return R.error("未查询到要审核的采购订单信息");
		}

		String errorMsg = "";
		for(int i=0;i<sonList.size();i++){
			Map<String,Object> sonItem = sonList.get(i);

			if(checkUtil.isNullByObject(sonItem.get("sku"))){
				errorMsg += "子件"+sonItem.get("skuCode")+"的SKU属性为空；";
				continue;
			}
			if(checkUtil.isNullByObject(sonItem.get("realitySku"))){
				errorMsg += "子件"+sonItem.get("skuCode")+"的实际SKU属性为空；";
				continue;
			}
			if(!sonItem.get("sku").toString().equals(sonItem.get("realitySku").toString())){
				errorMsg += "子件"+sonItem.get("skuCode")+"SKU属性不一致，请确认！";
			}
		}
		if(!"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		return specialExamine(goodsId, planBid,operateStatus);
	}



	//特殊审核 -> 不验证SKU属性
	@Override
	public R specialExamine(Long goodsId,String planBid,int operateStatus) throws Exception{
		//获取可审核的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getExamineStatus();
		//验证
		List<TcgPurchaseByOrder> tcgPurchaseOrderList = new TcgPurchaseByOrder()
				.setPurchasePlanGoodsId(goodsId)
				.setPlanBid(planBid)
				.setOperateStatus(operateStatus)
				.where("A.OrderStatus IN ("+TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList)+")")
				.setStatus(1)
				.queryList();
		if(tcgPurchaseOrderList ==null || tcgPurchaseOrderList.size()<=0){
			return R.error("未查询到可以审核的采购订单信息");
		}
		for(TcgPurchaseByOrder tcgPurchaseOrder:tcgPurchaseOrderList){
			boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,tcgPurchaseOrder.getOrderStatus());
			//验证状态
			if(!statusIsPass){
				return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行审核");
			}

			//验证商议订单金额（含运）不等于实际订单金额（含运）
			if(tcgPurchaseOrder.getOrderAmountDiscuss() !=null && tcgPurchaseOrder.getOrderAmount() !=null){
				if(tcgPurchaseOrder.getOrderAmountDiscuss().compareTo(tcgPurchaseOrder.getOrderAmount())!=0){
					return R.error("商议订单金额（含运）不等于实际订单金额（含运），不能做订单审核");
				}
			}

			//验证子件单价
			List<TcgPurchaseByOrderSon> orderSonList = new TcgPurchaseByOrderSon().setPid(tcgPurchaseOrder.getId()).queryList();
			for(TcgPurchaseByOrderSon sonInfo : orderSonList){
				if(checkUtil.isNullByObject(sonInfo.getRealityPrice())
						|| checkUtil.isNullByObject(sonInfo.getSubRealityPrice())
						|| checkUtil.isNullByObject(sonInfo.getRealityCost())
						|| checkUtil.isNullByObject(sonInfo.getSubCostPrice())){
					return R.error("子件单价未进行计算，请重新同步下订单信息");
				}

				//验证是否重复订单
				int planSonNum = new TcgPurchaseByOrderSon()
						.addLeftJoin("TCG_PurchaseByOrder B ON B.Id = A.Pid")
						.where("B.Status = 1")
						.setPurchasePlanSonId(sonInfo.getPurchasePlanSonId()).count();
				if(planSonNum>=2){
					return R.error("子件"+sonInfo.getSubCode()+"，重复下单，请确认");
				}
			}




			//***开始：再次匹配1688订单信息，如信息不一致需提示：订单信息与1688后台信息不一致，请核对。***
			{
				BigDecimal orderAmountByApi = api1688Service.get1688OrderAmountApi(tcgPurchaseOrder.getBid());
				if (orderAmountByApi == null) {
					return R.error("匹配一次1688订单信息失败，请重试。");
				}

				BigDecimal orderAmountByOld = tcgPurchaseOrder.getOrderAmount();
				if (orderAmountByOld.compareTo(orderAmountByApi) != 0) {
					return R.error("订单信息与1688后台信息不一致，请核对。");
				}
			}
			//***结束：再次匹配1688订单信息，如信息不一致需提示：订单信息与1688后台信息不一致，请核对。***
		}

		//审核操作
		for(TcgPurchaseByOrder tcgPurchaseOrder:tcgPurchaseOrderList){
			specialExamineByOneRow(tcgPurchaseOrder);
		}

		return R.ok();
	}

	 */



	//审核
	@Override
	public R examine(String bid) throws Exception{
		//获取可审核的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getExamineStatus();

		List<Map<String,Object>> sonList = new TcgPurchaseByOrder()
				.addLeftJoin("TCG_PurchaseByOrderSon B ON B.Pid = A.Id")
				.addField("B.Sku sku")
				.addField("B.SkuCode skuCode")
				.addField("B.RealitySku realitySku")
				//.setPurchasePlanGoodsId(goodsId)
				//.setPlanBid(planBid)
				//.setOperateStatus(operateStatus)
				.setBid(bid)
				.where("A.OrderStatus IN ("+TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList)+")")
				//.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688.value)
				.setStatus(1)
				.queryMap();

		//验证子列表 SKU属性与实际SKU属性是否一致
		//List<TcgPurchaseByOrderSon> sonList = new TcgPurchaseByOrderSon().setPid(id).queryList();
		if(sonList ==null || sonList.size()<=0){
			return R.error("未查询到要审核的采购订单信息");
		}

		String errorMsg = "";
		for(int i=0;i<sonList.size();i++){
			Map<String,Object> sonItem = sonList.get(i);

			if(checkUtil.isNullByObject(sonItem.get("sku"))){
				errorMsg += "子件"+sonItem.get("skuCode")+"的SKU属性为空；";
				continue;
			}
			if(checkUtil.isNullByObject(sonItem.get("realitySku"))){
				errorMsg += "子件"+sonItem.get("skuCode")+"的实际SKU属性为空；";
				continue;
			}
			if(!sonItem.get("sku").toString().equals(sonItem.get("realitySku").toString())){
				errorMsg += "子件"+sonItem.get("skuCode")+"SKU属性不一致，请确认！";
			}
		}
		if(!"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		return specialExamine(bid);
	}



	//特殊审核 -> 不验证SKU属性
	@Override
	public R specialExamine(String bid) throws Exception{
		//获取可审核的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getExamineStatus();
		//验证
		List<TcgPurchaseByOrder> tcgPurchaseOrderList = new TcgPurchaseByOrder()
				//.setPurchasePlanGoodsId(goodsId)
				//.setPlanBid(planBid)
				//.setOperateStatus(operateStatus)
				.setBid(bid)
				.where("A.OrderStatus IN ("+TcgPurchaseByOrderEnum.OrderStatus.getValueSearchByList(statusList)+")")
				.setStatus(1)
				.queryList();
		if(tcgPurchaseOrderList ==null || tcgPurchaseOrderList.size()<=0){
			return R.error("未查询到可以审核的采购订单信息");
		}
		for(TcgPurchaseByOrder tcgPurchaseOrder:tcgPurchaseOrderList){
			boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,tcgPurchaseOrder.getOrderStatus());
			//验证状态
			if(!statusIsPass){
				return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行审核");
			}

			//验证商议订单金额（含运）不等于实际订单金额（含运）
			if(tcgPurchaseOrder.getOrderAmountDiscuss() !=null && tcgPurchaseOrder.getOrderAmount() !=null){
				if(tcgPurchaseOrder.getOrderAmountDiscuss().compareTo(tcgPurchaseOrder.getOrderAmount())!=0){
					return R.error("商议订单金额（含运）不等于实际订单金额（含运），不能做订单审核");
				}
			}

			//验证子件单价
			List<TcgPurchaseByOrderSon> orderSonList = new TcgPurchaseByOrderSon().setPid(tcgPurchaseOrder.getId()).queryList();
			for(TcgPurchaseByOrderSon sonInfo : orderSonList){
				if(checkUtil.isNullByObject(sonInfo.getRealityPrice())
						|| checkUtil.isNullByObject(sonInfo.getSubRealityPrice())
						|| checkUtil.isNullByObject(sonInfo.getRealityCost())
						|| checkUtil.isNullByObject(sonInfo.getSubCostPrice())){
					return R.error("子件单价未进行计算，请重新同步下订单信息");
				}

				//验证是否重复订单
				int planSonNum = new TcgPurchaseByOrderSon()
						.addLeftJoin("TCG_PurchaseByOrder B ON B.Id = A.Pid")
						.where("B.Status = 1")
						.setPurchasePlanSonId(sonInfo.getPurchasePlanSonId()).count();
				if(planSonNum>=2){
					return R.error("子件"+sonInfo.getSubCode()+"，重复下单，请确认");
				}
			}




			//***开始：再次匹配1688订单信息，如信息不一致需提示：订单信息与1688后台信息不一致，请核对。***
			{
				BigDecimal orderAmountByApi = api1688Service.get1688OrderAmountApi(tcgPurchaseOrder.getBid());
				if (orderAmountByApi == null) {
					return R.error("匹配一次1688订单信息失败，请重试。");
				}

				BigDecimal orderAmountByOld = tcgPurchaseOrder.getOrderAmount();
				if (orderAmountByOld.compareTo(orderAmountByApi) != 0) {
					return R.error("订单信息与1688后台信息不一致，请核对。");
				}
			}
			//***结束：再次匹配1688订单信息，如信息不一致需提示：订单信息与1688后台信息不一致，请核对。***
		}

		//审核操作
		for(TcgPurchaseByOrder tcgPurchaseOrder:tcgPurchaseOrderList){
			specialExamineByOneRow(tcgPurchaseOrder);
		}

		return R.ok();
	}




	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public void specialExamineByOneRow(TcgPurchaseByOrder tcgPurchaseOrder) throws Exception{
		try {
			lock.lock(); // 加锁

			TcgPurchaseOrderPay hasAdd = new TcgPurchaseOrderPay()
					.setPlanBid(tcgPurchaseOrder.getPlanBid())
					.setPurchasePlanGoodsId(tcgPurchaseOrder.getPurchasePlanGoodsId())
					.setPurchaseOrderBid(tcgPurchaseOrder.getBid())
					.queryFirst();

			if(hasAdd==null || hasAdd.getId()==null){
				//解冻计划单冻结的金额
				tcwAccountCountForCompanyService.thaw(tcgPurchaseOrder.getVgsbm(), tcgPurchaseOrder.getOrderAmountExpect(),
						TcwOperateFrozenRunningEnum.DocumentType.TCG_PurchaseByOrder.value,
						tcgPurchaseOrder.getId(),
						tcgPurchaseOrder.getBid(),
						null);

				TpProductActive tpProductActive = new TpProductActive().setCode(tcgPurchaseOrder.getSpBm()).queryFirst();
				String remark = tcgPurchaseOrder.getBid()+","+tcgPurchaseOrder.getSpBm()+tpProductActive.getName();
				//新增业务流水
				//实际订单金额（含运
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
						tcgPurchaseOrder.getVgsbm(), "GS0607",
						TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name,
						tcgPurchaseOrder.getPurchaseOrderAmount().negate(),
						tcgPurchaseOrder.getCreateTime(),new Date(),
						remark,
						tcgPurchaseOrder.getBid(), new Date());
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
						"GS0607",tcgPurchaseOrder.getVgsbm(),
						TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name,
						tcgPurchaseOrder.getPurchaseOrderAmount(),
						tcgPurchaseOrder.getCreateTime(),new Date(),
						remark,
						tcgPurchaseOrder.getBid(), new Date());

				//采购服务费
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
						tcgPurchaseOrder.getVgsbm(), "GS0607",
						TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name,
						tcgPurchaseOrder.getServiceCharge().negate(),
						tcgPurchaseOrder.getCreateTime(),new Date(),
						remark,
						tcgPurchaseOrder.getBid(), new Date());
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(
						"GS0607",tcgPurchaseOrder.getVgsbm(),
						TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name,
						tcgPurchaseOrder.getServiceCharge(),
						tcgPurchaseOrder.getCreateTime(),new Date(),
						remark,
						tcgPurchaseOrder.getBid(), new Date());

			}

			//修改状态、审批信息
			tcgPurchaseOrder.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.API_NEED_PAY.value);
			tcgPurchaseOrder.setAuditingUserId(ShiroUtils.getUserId());
			tcgPurchaseOrder.setAuditingTime(new Date());
			tcgPurchaseByOrderMapper.update(tcgPurchaseOrder);

			//生成采购付款单
			String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseOrderPay);
			TcgPurchaseOrderPay tcgPurchaseOrderPay = new TcgPurchaseOrderPay()
					.setBid(bid)
					.setPlanBid(tcgPurchaseOrder.getPlanBid())
					.setPurchasePlanGoodsId(tcgPurchaseOrder.getPurchasePlanGoodsId())
					.setPurchaseOrderBid(tcgPurchaseOrder.getBid())
					.setStatus(1)
					;


			if(hasAdd!=null && hasAdd.getId()!=null){
				tcgPurchaseOrderPay.setId(hasAdd.getId());
				tcgPurchaseOrderPayMapper.update(tcgPurchaseOrderPay);
			}else {
				tcgPurchaseOrderPayMapper.insert(tcgPurchaseOrderPay);
			}
			lock.unlock(); // 释放锁
		}finally {
			try {
				lock.unlock(); // 确保释放锁
			}catch (Exception e){}
		}


	}



	//更换渠道
	@Override
	//@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R changeChannel(Long id) throws Exception{
		List<TcgPurchaseByOrderSon> sonList = new TcgPurchaseByOrderSon().setPid(id).queryList();
		TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setId(id).queryFirst();
		if(sonList ==null || sonList.size()<=0 || entity==null || entity.getBid()==null){
			return R.error("未查询到要更换渠道的采购订单信息");
		}

		//获取可更换渠道的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getChangeChannelStatus();

		//验证状态
		boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());
		//验证状态
		if(!statusIsPass){
			return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行更换渠道");
		}

		List<TcgPurchaseByOrderSon> sonListByNew = new ArrayList<>();
		String errorMsg = "";
		int row = 0;
		String supplierId = "";
		for(TcgPurchaseByOrderSon sonInfo:sonList){
			//获取铺货信息
			TcgDistribution tcgDistribution = new TcgDistribution().setScode(sonInfo.getSubCode()).queryFirst();
			if(tcgDistribution==null || tcgDistribution.getId()==null){
				errorMsg += "子件"+sonInfo.getSkuCode()+"的铺货信息为空；";
				continue;
			}
			sonInfo.setGoodsId(tcgDistribution.getGoodsId());//1688铺货商品ID
			sonInfo.setSku(tcgDistribution.getSkupRoperty());//SKU属性
			sonInfo.setSkuId(tcgDistribution.getSkuId());//skuId
			sonInfo.setSpecId(tcgDistribution.getSpecId());//specId
			sonInfo.setTradeName(tcgDistribution.getName());//商品标题
			sonInfo.setSkuCode(tcgDistribution.getSkuCode());//sku编码
			sonInfo.setSupplierId(tcgDistribution.getSupplierId());//供应商id
			sonListByNew.add(sonInfo);
			if(row==0){
				supplierId = tcgDistribution.getSupplierId();
			}
			if(row!=0 && !supplierId.equals(tcgDistribution.getSupplierId())){
				errorMsg += "子件"+sonInfo.getSkuCode()+"的供应商信息与其他的子件不一致请核对；";
			}
			row++;
		}
		if(!"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		int orderStatusByOld = entity.getOrderStatus();

		boolean isReCread = false;

		//获取更换渠道时，需要访问1688进行订单取消操作的状态
		List<TcgPurchaseByOrderEnum.OrderStatus> cancel1688StatusList = TcgPurchaseByOrderEnum.OrderStatus.getCancel1688WhenChangeChannelStatus();

		//验证状态
		boolean isCancel1688 = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(cancel1688StatusList,orderStatusByOld);

		//订单已生成的取消订单
		if(isCancel1688){
			isReCread = true;
			String cancelReason = "更换渠道";
			//取消订单
			R res = api1688Service.cancel1688Order(entity.getBid(),cancelReason,false);
			if(res.getCode().equals(R.Code.SUCCESS.value)){//成功
				/*
				cancelOrderByOneRow(
						entity.getPurchasePlanGoodsId(),
						entity.getPlanBid(),
						entity.getOperateStatus(),
						entity.getOrderStatus(),
						cancelReason,
						false
				);
				 */
			}else {//失败
				return res;
			}
		}

		TcgPurchaseByOrder entityByNew = new TcgPurchaseByOrder()
				.setId(id)
				.setStatus(0)
				.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.CANCEL_YB_1688.value)
				.setOperateStatus(TcgPurchaseByOrderEnum.OperateStatus.CHANGE_CHANNEL_CANCEL.value);
		//变更原信息订单状态
		tcgPurchaseByOrderMapper.update(entityByNew);

		TcgPurchaseByPlan tcgPurchaseByPlan = new TcgPurchaseByPlan().setBid(entity.getPlanBid()).queryFirst();
		//重新新增一条订单
		TcgPurchaseAddress tcgPurchaseAddress = new TcgPurchaseAddress().setId(tcgPurchaseByPlan.getPurchaseAddressId()).queryFirst();

		//获取单号
		String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseByOrder);
		//int oldOrderStatus = orderStatusByOld;
		entity.setBid(bid);
		entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.ORDER_PRODUCE.value);//订单已创建状态
		entity.setAliResult("");//变更状态
		//entity.setOperateStatus(TcgPurchaseByOrderEnum.OperateStatus.NORMAL.value);
		//拼接api采购地址
		entity.setApiAddrSend(getApiAddr(tcgPurchaseAddress,entity));
		tcgPurchaseByOrderMapper.insert(entity);

		//新增子表 - 渠道信息
		for(TcgPurchaseByOrderSon sonInfo:sonListByNew){
			//将原子表信息状态变更
			sonInfo.setStatus(0);
			tcgPurchaseByOrderSonMapper.update(sonInfo);
			//新增新的子表信息
			sonInfo.setPid(entity.getId());
			sonInfo.setStatus(1);
			tcgPurchaseByOrderSonMapper.insert(sonInfo);
		}


		if(isReCread){
			//重新创建订单
			api1688Service.create1688Order(bid);
			//api1688Service.get1688OrderDetail(bid);
		}

		return R.ok();
	}





	//占用红包
	@Override
	//@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R occupy(Long id) throws Exception{
		List<TcgPurchaseByOrderSon> sonList = new TcgPurchaseByOrderSon().setPid(id).queryList();
		TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setId(id).queryFirst();
		if(sonList ==null || sonList.size()<=0 || entity==null || entity.getBid()==null){
			return R.error("未查询到要占用红包的采购订单信息");
		}

		/*
		int hasDo = new TcgPurchaseByOrder()
				.setPlanBid(entity.getPlanBid())
				.setPurchasePlanGoodsId(entity.getPurchasePlanGoodsId())
				.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_OCCUPY_COUPON.value)
				.count();
		if(hasDo>0){
			return R.error("该订单已操作过占用红包");
		}
		 */

		//获取可进行的状态信息
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getOccupyStatus();

		//验证状态
		boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());
		//验证状态
		if(!statusIsPass){
			return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行操作");
		}

		TcgPurchaseByOrder entityByOld = new TcgPurchaseByOrder()
				.setId(id)
				.setStatus(0)
				.setOperateStatus(TcgPurchaseByOrderEnum.OperateStatus.OCCUPY_COUPON.value)
				.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_OCCUPY_COUPON.value)
				;
		//变更原信息订单状态
		tcgPurchaseByOrderMapper.update(entityByOld);

		TcgPurchaseByPlan tcgPurchaseByPlan = new TcgPurchaseByPlan().setBid(entity.getPlanBid()).queryFirst();
		//重新新增一条订单
		TcgPurchaseAddress tcgPurchaseAddress = new TcgPurchaseAddress().setId(tcgPurchaseByPlan.getPurchaseAddressId()).queryFirst();
		//拼接api采购地址
		entity.setApiAddrSend(getApiAddr(tcgPurchaseAddress,entity));

		//获取单号
		String bid = commonApiService.getCommonNextBid(MenuId.TCG_PurchaseByOrder);
		entity.setBid(bid);
		//entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.PRODUCE_YB_1688_WITH_COUPON.value);//订单已生成（含红包）状态
		entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.ORDER_PRODUCE.value);//订单已创建状态
		entity.setAliResult("");//变更状态
		tcgPurchaseByOrderMapper.insert(entity);

		//新增子表 - 渠道信息
		for(TcgPurchaseByOrderSon sonInfo:sonList){
			//将原子表信息状态变更
			sonInfo.setStatus(0);
			tcgPurchaseByOrderSonMapper.update(sonInfo);
			//新增新的子表信息
			sonInfo.setPid(entity.getId());
			sonInfo.setStatus(1);
			tcgPurchaseByOrderSonMapper.insert(sonInfo);
		}

		//重新创建订单
		api1688Service.create1688Order(bid);
		//api1688Service.get1688OrderDetail(bid);

		return R.ok();
	}

	//订单取消-变更状态
	@Override
	public R cancelOrder(List<Map<String, Object>> detailList,String cancelReason) throws Exception{
		for(Map<String, Object> item:detailList){
			Long purchasePlanGoodsId = Long.parseLong(item.get("purchasePlanGoodsId").toString());
            String planBid = item.get("planBid").toString();
			int operateStatus = Integer.parseInt(item.get("operateStatus").toString());
			int orderStatus = Integer.parseInt(item.get("orderStatus").toString());
			cancelOrderByOneRow(purchasePlanGoodsId,planBid,operateStatus,orderStatus,cancelReason,true);
		}

		return R.ok();
	}

	@Override
	public R cancelOrderByOneRow(Long purchasePlanGoodsId,String planBid,int operateStatus,int orderStatus,String cancelReason,boolean planIsCancel){
		List<TcgPurchaseByOrder> entityList = new TcgPurchaseByOrder()
				.setPurchasePlanGoodsId(purchasePlanGoodsId)
				.setPlanBid(planBid)
				.setOrderStatus(orderStatus)
				//.setStatus(1)
				.setOperateStatus(operateStatus)
				.queryList();
		for(TcgPurchaseByOrder entity:entityList){
			//修改采购订单状态
			//TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setId(Long.parseLong(item.get("id").toString())).queryFirst();
			entity.setOrderStatus(TcgPurchaseByOrderEnum.OrderStatus.CANCEL_YB_1688.value);
			String remarkOld = "";
			if(entity.getRemark()!=null){
				remarkOld = entity.getRemark();
			}
			entity.setAliResult("取消成功");//变更状态
			entity.setRemark(remarkOld+cancelReason);
			entity.setAliState("cancel");
			tcgPurchaseByOrderMapper.update(entity);
		}

		if(planIsCancel && operateStatus==TcgPurchaseByOrderEnum.OperateStatus.NORMAL.value){
			//修改采购计划单状态
			TcgPurchasePlanGoods tcgPurchasePlanGoods = new TcgPurchasePlanGoods().setId(purchasePlanGoodsId).queryFirst();
			tcgPurchasePlanGoods.setOrderStatus(TcgPurchasePlanGoodsEnum.OrderStatus.ORDER_DEL.value);
			tcgPurchasePlanGoodsMapper.update(tcgPurchasePlanGoods);
		}

		return R.ok();
	}




	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);

		TcgPurchaseByOrder entity = JSON.parseObject(JSON.toJSONString(params), TcgPurchaseByOrder.class);

		tcgPurchaseByOrderMapper.update(entity);
		return R.ok(AddDto.gotoEdit("/web/purchase/tcgPurchaseByOrder/toUpdate?id=" + entity.getId()));
	}



	//订单刷新
	@Override
	public R refreshOrder(List<Map<String, Object>> detailList) throws Exception{
		String orderNos = "";

		int doCount = 0;
		String resMsg = "";
		R res = null;

		//获取可以进行订单同步的状态
		List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getRefreshStatus();

		for (int i = 0; i < detailList.size(); i++) {
			Map<String, Object> info = detailList.get(i);

			//验证
			TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setId(Long.parseLong(info.get("id").toString())).queryFirst();
			if(entity==null || entity.getBid()==null){
				res = R.error("未查询到要取消的采购订单信息");
			}else {

				//验证状态
				boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());

				//验证状态
				if(!statusIsPass){
					res = R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行同步");
				}else {
					if("".equals(orderNos)){
						orderNos = info.get("bid").toString();
					}else {
						orderNos +="," + info.get("bid").toString();
					}
				}
			}

			if(res!=null && res.getCode()==1){
				resMsg += (info.get("bid")!=null?"单号："+info.get("bid"):"")+"；"+res.getMsg()+"</br>";
			}else{
				doCount ++;
			}
		}

		R resByEnd = R.ok();
		if(!"".equals(orderNos)){
			resByEnd = api1688Service.get1688OrderDetail(orderNos);
		}
		if(resByEnd.getCode()==0){
			resMsg = "成功同步"+doCount+"条采购订单的渠道信息</br>"+resMsg;
		}else {
			resMsg = "操作失败，"+resByEnd.getMsg()+"</br>"+resMsg;
		}
		return R.ok(resMsg);
	}



	//计算子件单价信息
	@Override
	public void countSubRealityPrice(TcgPurchaseByOrder entity) throws Exception{

		logger.info("*******开始计算子件单价信息**********");
		List<TcgPurchaseByOrderSon> orderSonList = new TcgPurchaseByOrderSon()
				.setPid(entity.getId())
				.setOrderby("A.Id")
				.queryList();

		BigDecimal noLastRowCostPriceAdd = BigDecimal.ZERO;
		BigDecimal noLastRowRealityCostAdd = BigDecimal.ZERO;

		BigDecimal orderAmount = entity.getOrderAmount();//实际订单金额/采购成本价（含运）
		BigDecimal serviceCharge = entity.getServiceCharge();//服务费
		BigDecimal freightCharge =entity.getFreightCharge();//实际运费
		logger.info("实际订单金额/采购成本价（含运）：" + orderAmount);
		logger.info("服务费：" + serviceCharge);
		logger.info("实际运费：" + freightCharge);

		BigDecimal orderAmountBySale = orderAmount.add(serviceCharge);//采购销售价
		logger.info("采购销售价=采购成本价（含运）+服务费：" + orderAmount + "+" + serviceCharge + "=" + orderAmountBySale);

		for(int i=0;i<orderSonList.size();i++){
			TcgPurchaseByOrderSon tcgPurchaseOrderSon = orderSonList.get(i);

			//获取计划单子件信息
			TcgPurchaseByPlanSon planSon = new TcgPurchaseByPlanSon().setId(tcgPurchaseOrderSon.getPurchasePlanSonId()).queryFirst();
			logger.info("*********************开始计算：" + entity.getBid()+"，子件："+tcgPurchaseOrderSon.getSubCode()+"****************************");

			//BigDecimal subTotalPrice = planSon.getSubTotalPrice();//子件预估总价

			int subTotalAmount = planSon.getSubTotalAmount();//子件采购总数
			BigDecimal subTotalPrice = tcgPurchaseOrderSon.getRealityPrice().multiply(new BigDecimal(subTotalAmount));//实际总价
			//logger.info("子件预估总价：" + subTotalPrice);
			logger.info("子件实际总价：" + subTotalPrice);
			logger.info("子件采购总数：" + subTotalAmount);

			int scaleIng = 10;//计算过程保留的小数点

			BigDecimal costPriceTotal = BigDecimal.ZERO;//子件总价（采购成本）
			BigDecimal subCostPrice = BigDecimal.ZERO;//子件单价（采购成本）
			BigDecimal realityCost = BigDecimal.ZERO;//子件总价（采购销售）
			BigDecimal subRealityPrice = BigDecimal.ZERO;//子件单价（采购销售）

			//计算总价占比 = 实际总价 ÷ 采购成本价（含运）
			BigDecimal totalRatio = BigDecimal.ZERO;
			if(orderAmount.compareTo(BigDecimal.ZERO)!=0){
				totalRatio = subTotalPrice.divide(orderAmount, scaleIng, RoundingMode.HALF_UP);
			}
			logger.info("总价占比 = 实际总价 ÷ 采购成本价（含运）：" + subTotalPrice + "÷" + orderAmount + "=" + totalRatio+"（保留"+scaleIng+"位小数）");

			if(i==orderSonList.size()-1){
				logger.info("!!!属于最后一条子件!!!");

				//计算【最后一条】子件总价（采购成本） = 采购成本价（含运） - 其他子件子件总价（采购成本）
				costPriceTotal = orderAmount.subtract(noLastRowCostPriceAdd);
				logger.info("【最后一条】子件总价（采购成本） = 采购成本价（含运） - 其他子件子件总价（采购成本）：" + orderAmount + "-" + noLastRowCostPriceAdd + "=" + costPriceTotal);
				//保留2位小数
				costPriceTotal = costPriceTotal.setScale(2, RoundingMode.HALF_UP);
				logger.info("【最后一条】子件总价（保留2位小数） = " + costPriceTotal);


				//计算【最后一条】子件总价（采购销售） = 采购销售价 - 其他子件子件总价（采购销售）
				realityCost = orderAmountBySale.subtract(noLastRowRealityCostAdd);
				logger.info("【最后一条】子件总价（采购销售） = 采购销售价 - 其他子件子件总价（采购销售）：" + orderAmountBySale + "-" + noLastRowRealityCostAdd + "=" + costPriceTotal);
				//保留2位小数
				realityCost = realityCost.setScale(2, RoundingMode.HALF_UP);
				logger.info("【最后一条】子件总价（采购销售）（保留2位小数） = " + realityCost);

			}else {
				logger.info("!!!不是最后一条子件!!!");
				//计算子件总价（采购成本） = 采购成本价（含运） * 总价占比
				costPriceTotal = orderAmount.multiply(totalRatio);
				logger.info("子件总价（采购成本） = 采购成本价（含运） * 总价占比：" + orderAmount + "*" + totalRatio + "=" + costPriceTotal);
				//保留2位小数
				costPriceTotal = costPriceTotal.setScale(2, RoundingMode.HALF_UP);
				logger.info("子件总价（保留2位小数） = " + costPriceTotal);
				//累加子件总价（采购成本）
				noLastRowCostPriceAdd = noLastRowCostPriceAdd.add(costPriceTotal);


				//计算子件总价（采购销售） = 采购销售价 * 总价占比
				realityCost = orderAmountBySale.multiply(totalRatio);
				logger.info("子件总价（采购销售） = 采购销售价 * 总价占比：" + orderAmountBySale + "*" + totalRatio + "=" + realityCost);
				//保留2位小数
				realityCost = realityCost.setScale(2, RoundingMode.HALF_UP);
				logger.info("子件总价（采购销售）（保留2位小数） = " + realityCost);
				noLastRowRealityCostAdd = noLastRowRealityCostAdd.add(realityCost);

			}

			//计算：子件单价（采购成本） = 子件总价（采购成本） ÷ 采购数量
			subCostPrice = costPriceTotal.divide(new BigDecimal(subTotalAmount), scaleIng, RoundingMode.HALF_UP);
			logger.info("子件单价（采购成本） = 子件总价（采购成本） ÷ 采购数量：" + costPriceTotal + "÷" + subTotalAmount + "=" + subCostPrice+"（保留"+scaleIng+"位小数）");
			//保留4位小数
			subCostPrice = subCostPrice.setScale(4, RoundingMode.HALF_UP);
			logger.info("子件单价（采购成本）（保留4位小数） = " + subCostPrice);

			//计算：子件单价（采购销售） = 子件总价（采购销售） ÷ 采购数量
			subRealityPrice = realityCost.divide(new BigDecimal(subTotalAmount), scaleIng, RoundingMode.HALF_UP);
			logger.info("子件单价（采购销售） = 子件总价（采购销售） ÷ 采购数量：" + realityCost + "÷" + subTotalAmount + "=" + subRealityPrice+"（保留"+scaleIng+"位小数）");
			//保留4位小数
			subRealityPrice = subRealityPrice.setScale(4, RoundingMode.HALF_UP);
			logger.info("子件单价（采购销售）（保留4位小数） = " + subRealityPrice);

			tcgPurchaseOrderSon.setCostPriceTotal(costPriceTotal);
			tcgPurchaseOrderSon.setSubCostPrice(subCostPrice);
			tcgPurchaseOrderSon.setRealityCost(realityCost);
			tcgPurchaseOrderSon.setSubRealityPrice(subRealityPrice);
			tcgPurchaseByOrderSonMapper.update(tcgPurchaseOrderSon);
		}


		logger.info("*******结束计算**********");
	}


	//更新订单管理状态
	@Override
	public R updateOrderManageStatus(String bid) throws Exception{
		//获取采购订单子列表信息
		List<Map<String,Object>> sonList = new TcgPurchaseByOrderSon()
				.addLeftJoin("TP_ProductBasisComponent B ON B.Code = A.SubCode")//商品子件信息表
				.addField("B.NegotiatedPrice AS negotiatedPrice")//协议价

				.addLeftJoin("TCG_PurchaseByOrder C ON C.Id = A.Pid")//订单表
				.addField("C.OrderAmountDiscuss AS orderAmountDiscuss")//商议订单金额（含运）
				.addField("C.OrderAmount AS orderAmount")//实际订单金额（含运）

				.addLeftJoin("TCG_PurchaseByPlanSon D ON D.Id = A.PurchasePlanSonId")
				.addField("D.SubTotalAmount AS subTotalAmount")//子件采购总数

				.where("C.Bid = '"+bid+"'")
				.queryMap();


		//获取配置信息
		List<TbStaticConfig> configByOrder = new TbStaticConfig().setKeyOne("TCG_PurchaseOrderSon").queryList();
		logger.info("更新订单管理状态：" + sonList);

		if(sonList!=null && sonList.size()>0 && configByOrder!=null && configByOrder.size()>0){

			for(Map<String,Object> sonInfo:sonList){
				StringBuffer orderManageStatus = new StringBuffer();

				//旧：价格不匹配 => 子件实际单价＞子件采购价格*1.1
				//新（20250206改）：价格不匹配 => 子件实际单价＞子件采购价格*1
				if(sonInfo.get("realityPrice")!=null && sonInfo.get("subRealityPrice")!=null){
					BigDecimal realityPrice = new BigDecimal(sonInfo.get("realityPrice").toString());//子件实际单价
					BigDecimal subRealityPrice = new BigDecimal(sonInfo.get("subRealityPrice").toString());//子件实际单价

					//旧：1.1从TB_StaticConfig表中获取
					//新（20250206改）：1从TB_StaticConfig表中获取
					TbStaticConfig tbStaticConfigByRadio = configByOrder.stream()
							.filter(item->item.getKeyTwo().equals("OrderManageStatus-SubPrice_Ratio"))
							.collect(Collectors.toList())
							.get(0);
					if(realityPrice.compareTo(subRealityPrice.multiply(new BigDecimal(tbStaticConfigByRadio.getName())))>0){
						orderManageStatus.append("价格");
					}
				}

				//协议价不匹配 => 子件实际单价＞协议价 , 协议价为空为0不判断
				if(sonInfo.get("realityPrice")!=null && sonInfo.get("negotiatedPrice")!=null){
					BigDecimal realityPrice = new BigDecimal(sonInfo.get("realityPrice").toString());//子件实际单价
					BigDecimal negotiatedPrice = new BigDecimal(sonInfo.get("negotiatedPrice").toString());//协议价
					if(negotiatedPrice.compareTo(BigDecimal.ZERO)!=0){
						if(realityPrice.compareTo(negotiatedPrice)>0){
							if(orderManageStatus.length()>0){
								orderManageStatus.append("、");
							}
							orderManageStatus.append("协议价");
						}
					}

				}


				//运费不匹配 => 首重12元+5元/公斤；抛系数6000


				//商议订单金额不匹配 => 实际订单金额（含运） != 商议订单金额（含运）
				if(sonInfo.get("orderAmountDiscuss")!=null && sonInfo.get("orderAmount")!=null){
					if(new BigDecimal(sonInfo.get("orderAmountDiscuss").toString()).compareTo(new BigDecimal(sonInfo.get("orderAmount").toString()))!=0){
						if(orderManageStatus.length()>0){
							orderManageStatus.append("、");
						}
						orderManageStatus.append("商议订单金额");
					}
				}

				if(orderManageStatus.length()>0){
					orderManageStatus.append("不匹配；");
				}

				//需议价 => 议价：≥100套，≥2000元
				if(sonInfo.get("realityCost")!=null && sonInfo.get("subTotalAmount")!=null){
					//100套、2000元 的判断标准从TB_StaticConfig表中获取
					TbStaticConfig tbStaticConfigByNum = configByOrder.stream()
							.filter(item->item.getKeyTwo().equals("OrderManageStatus-NeedNegotiated_Num"))
							.collect(Collectors.toList())
							.get(0);

					TbStaticConfig tbStaticConfigByPrice = configByOrder.stream()
							.filter(item->item.getKeyTwo().equals("OrderManageStatus-NeedNegotiated_Price"))
							.collect(Collectors.toList())
							.get(0);
					if(new BigDecimal(sonInfo.get("subTotalAmount").toString()).compareTo(new BigDecimal(tbStaticConfigByNum.getName()))>0
						&& new BigDecimal(sonInfo.get("realityCost").toString()).compareTo(new BigDecimal(tbStaticConfigByPrice.getName()))>0){
						orderManageStatus.append("需议价；");
					}

				}
				TcgPurchaseByOrderSon sonEntity = new TcgPurchaseByOrderSon();//JSON.parseObject(JSON.toJSONString(sonInfo), TcgPurchaseByOrderSon.class);
				sonEntity.setId(Long.parseLong(sonInfo.get("id").toString()));
				//修改
				if(orderManageStatus.length()>0){
					sonEntity.setOrderManageStatus(orderManageStatus.toString());
				}else{
					sonEntity.setOrderManageStatus("正常");
				}
				logger.info("更新"+sonEntity.getId()+"订单管理状态：" + sonEntity.getOrderManageStatus());
				tcgPurchaseByOrderSonMapper.update(sonEntity);
			}

		}else {
			return R.error("更新订单管理状态出错，无判断对应的配置信息");
		}


		return R.ok();

	}




	//修改商议订单金额（含运）
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R updateOrderAmountDiscuss(String bid, String orderAmountDiscuss) throws Exception {
		TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setBid(bid).queryFirst();
		if(entity!=null && entity.getId()!=null){
			//获取可以进行修改商议订单金额（含运）的状态
			List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getUpdateOrderAmountDiscuss();

			//验证状态
			boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());

			//验证状态
			if(!statusIsPass){
				return R.error("需要在创建1688订单后才可进行商议订单金额的设置");
			}
			/*
			if(entity.getOrderAmount()==null){
				return R.error("需要在创建1688订单后才可进行商议订单金额的设置");
			}
			 */
			entity.setOrderAmountDiscuss(new BigDecimal(orderAmountDiscuss));
			tcgPurchaseByOrderMapper.update(entity);
			return updateOrderManageStatus(bid);
		}else {
			return R.error("单号有误");
		}
		//return R.ok();
	}




	//修改采购订单金额（含税）
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R updatePurchaseOrderAmount(String bid, String purchaseOrderAmount) throws Exception {
		TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setBid(bid).queryFirst();
		if(entity!=null && entity.getId()!=null){
			//获取可以进行修改采购订单金额（含税）的状态
			List<TcgPurchaseByOrderEnum.OrderStatus> statusList = TcgPurchaseByOrderEnum.OrderStatus.getUpdatePurchaseOrderAmount();

			//验证状态
			boolean statusIsPass = TcgPurchaseByOrderEnum.OrderStatus.checkStatus(statusList,entity.getOrderStatus());

			//验证状态
			if(!statusIsPass){
				return R.error("只有"+TcgPurchaseByOrderEnum.OrderStatus.getNameStrByList(statusList)+"的订单才可进行修改采购订单金额（含税）");
			}
			entity.setPurchaseOrderAmount(new BigDecimal(purchaseOrderAmount));
			//修改服务费
			entity.setServiceCharge(entity.getPurchaseOrderAmount().multiply(new BigDecimal("0.05")).setScale(2, BigDecimal.ROUND_HALF_UP));
			tcgPurchaseByOrderMapper.update(entity);
			return updateOrderManageStatus(bid);
		}else {
			return R.error("单号有误");
		}
		//return R.ok();
	}





	//编辑工作日志
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R workLog(Long id, String workLog) throws Exception {
		TcgPurchaseByOrder entity = new TcgPurchaseByOrder()
				.setId(id)
				.setWorkLog(workLog);
		tcgPurchaseByOrderMapper.update(entity);
		return R.ok();
	}

	/**
	 * 修改采购订单金额（含税）
	 * @date 2024-04-01
	 * fxz
	 * @param bid 单号
	 * @param negotiatedPrice  协议价
	 * @param spBm 商品编码
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R updateNegotiatedPrice(String bid, String negotiatedPrice, String spBm) throws Exception {
		TcgPurchaseByOrder entity = new TcgPurchaseByOrder().setBid(bid).queryFirst();
		if(entity!=null && entity.getId()!=null){
			if (spBm.equals(entity.getSpBm())){
				//协议价
				entity.setNegotiatedPrice(new BigDecimal(negotiatedPrice));
				tcgPurchaseByOrderMapper.update(entity);

				//更新协议价
				TcgPurchaseByOrderNp tcgPurchaseByOrderNp = new TcgPurchaseByOrderNp().setSpBm(spBm).queryFirst();
				if (tcgPurchaseByOrderNp != null){
					tcgPurchaseByOrderNp.setNegotiatedPrice(new BigDecimal(negotiatedPrice));
					tcgPurchaseByOrderNpMapper.update(tcgPurchaseByOrderNp);
				}else {
					TcgPurchaseByOrderNp tcgPurchaseByOrderNpNew = new TcgPurchaseByOrderNp();
					tcgPurchaseByOrderNpNew.setSpBm(spBm);
					tcgPurchaseByOrderNpNew.setNegotiatedPrice(new BigDecimal(negotiatedPrice));
					tcgPurchaseByOrderNpNew.setStatus(1);
					tcgPurchaseByOrderNpMapper.insert(tcgPurchaseByOrderNpNew);
				}
			}
			return R.ok("修改协议价成功!");
		}else {
			return R.error("单号有误");
		}
	}


}
